<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="路线名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入路线名称" />
      </el-form-item>
      <el-form-item label="归属地" prop="deptId">
        <el-tree-select
          check-strictly
          v-model="formData.deptId"
          :data="deptList"
          :props="defaultProps"
          node-key="id"
          placeholder="请选择归属地" />
      </el-form-item>
      <el-form-item label="实践点信息">
        <el-button @click="handleOpenSpotDialog">选择实践点</el-button>
        <ul class="line">
          <li class="line-item" v-for="(item, index) in formData.lineList" :key="item.id">
            <div>{{ item?.name }}</div>
            <div>
              <el-button size="small" @click="handleUp(index)">向上</el-button>
              <el-button size="small" @click="handleDown(index)">向下</el-button>
              <el-button size="small" @click="handleDelete(index)">删除</el-button>
            </div>
          </li>
        </ul>
      </el-form-item>
      <el-form-item label="备注" prop="description">
        <Editor v-model="formData.description" height="150px" />
      </el-form-item>

    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <Dialog title="选择实践点" v-model="spotDialogVisible">
    <el-row :gutter="20">
      <!-- 左侧部门树 -->
      <el-col :span="6" :xs="24">
        <ContentWrap class="h-1/1">
          <DeptTree @node-click="handleDeptNodeClick" />
        </ContentWrap>
      </el-col>
      <el-col :span="18" :xs="24">
        <!-- 列表 -->
        <ContentWrap>
          <el-table ref="spotRef" v-loading="loading" :data="list" :row-key="(row) => row.id" :stripe="true" :show-overflow-tooltip="true" @selection-change="handleSelectionChange">
            <el-table-column type="selection" :reserve-selection="true" width="55" />
            <el-table-column label="实践点名称" align="center" prop="name" />
          </el-table>
          <!-- 分页 -->
          <Pagination
  :total="total" small v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
            @pagination="getList" />
        </ContentWrap>
      </el-col>
    </el-row>

    <template #footer>
      <el-button @click="handleSelectConfirm" type="primary">确 定</el-button>
      <el-button @click="handleCloseSpotDialog">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { SpotApi, SpotVO } from '@/api/scenic/spot'
import { TripApi, TripVO } from '@/api/road/trip'
import { defaultProps, handleTree } from '@/utils/tree';
import * as DeptApi from '@/api/system/dept';
import DeptTree from './DeptTree.vue'

/** 线路 表单 */
defineOptions({ name: 'TripForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: undefined,
  description: undefined,
  deptId: undefined,
  lineList: [],
  lineNameList: [],
  spotIdList: []
})
const formRules = reactive({
  name: [{ required: true, message: '线路名称不能为空', trigger: 'blur' }],
  deptId: [{ required: true, message: '线路部门id不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const deptList = ref<Tree[]>([]) // 树形结构

const spotRef = ref()
const spotDialogVisible = ref(false) // 弹窗的是否展示
const loading = ref(true) // 列表的加载中
const list = ref<SpotVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  spotName: undefined,
  provinceId: undefined,
  cityId: undefined,
  districtId: undefined,
})

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await TripApi.getTrip(id)
      formData.value.description = formData.value.description || undefined
      // @ts-ignore
      formData.value.lineList = (formData.value?.lineList || []).map((item, index) => {
        return {
          id: item,
          name: formData.value.lineNameList[index]
        }
      })
    } catch(e) {
      console.log('>>>', e)
    } finally {
      formLoading.value = false
    }
  }
  // 加载部门树
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as TripVO
    // @ts-ignore
    data.spotIdList = (data?.lineList || []).map(item => item.id)
    if (formType.value === 'create') {
      await TripApi.createTrip(data)
      message.success(t('common.createSuccess'))
    } else {
      await TripApi.updateTrip(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    description: undefined,
    deptId: undefined,
    lineList: [],
    lineNameList: [],
    spotIdList: [],
  }
  formRef.value?.resetFields()
}

const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

/** 处理部门被点击 */
const handleDeptNodeClick = async (row) => {
  //@ts-ignore
  queryParams.provinceId = 100
  if(!row?.children || row.children?.length === 0) {
    queryParams.districtId = row.id
    queryParams.cityId = row.parentId
  } else if(row.parentId != 0){
    queryParams.cityId = row.id
    queryParams.districtId = undefined
  } else {
    queryParams.cityId = undefined
    queryParams.districtId = undefined
  }

  await getList()
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await SpotApi.getSpotPage(queryParams)
    list.value = data.list || []
    total.value = data.total || 0
  } finally {
    loading.value = false
  }
}

const handleOpenSpotDialog = () => {
  spotDialogVisible.value = true
  getList()
}

const handleSelectConfirm = () => {
  if(!formData.value?.lineList) {
    formData.value.lineList = [...multipleSelection.value]
  } else {
    formData.value.lineList.push(...multipleSelection.value)
  }

  handleCloseSpotDialog()
}

const handleCloseSpotDialog = () => {
  spotDialogVisible.value = false
  list.value = []
  spotRef.value.clearSelection()
}

const handleUp = (index) => {
  if(index === 0) return
  formData.value.lineList.splice(index,1,...formData.value.lineList.splice(index - 1, 1 , formData.value.lineList[index]));
}

const handleDown = (index) => {
  if(index === (formData.value.lineList.length - 1)) return
  formData.value.lineList.splice(index,1,...formData.value.lineList.splice(index + 1, 1 , formData.value.lineList[index]));
}

const handleDelete = (index) => {
  formData.value.lineList.splice(index, 1)
}
</script>

<style>
.line {
  display: block;
  width: 100%;
  padding-left: 0;
}
.line-item {
  display: flex;
  flex-flow: row nowrap;
  justify-content: space-between;
}
</style>
